package tech.aistar.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.entity.*;
import tech.aistar.service.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/post")
public class PostController {

    //日期类转化模板工具
    public static Date stringDateUtil(String dateStr) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return simpleDateFormat.parse(dateStr);
    }

    @Autowired
    private IHouseService houseService;
    @Autowired
    private ICotenancyRequireService cotenancyRequireService;
    @Autowired
    private IEnvironmentFacilityService environmentFacilityService;
    @Autowired
    private IImageService iImageService;
    @Autowired
    private ICostService iCostService;
    //检测房源是否已经存在
    @PostMapping("/checkHouseId/{number}/{name}")
    public @ResponseBody
    Result select(@PathVariable("number") String number,@PathVariable("name") String name, HttpServletRequest request) {
        Integer house_id = houseService.selectDoorPlate(number,name);
        if (house_id == null) {
            request.setAttribute("house_id", house_id);
            return new Result("200", "可以发布");
        } else {
            return new Result("500", "禁止发布");
        }
    }

    @PostMapping("/layui/upload/nginx")
    public @ResponseBody Result uploads(HttpServletRequest req,@RequestParam("file") MultipartFile file){
        //重新进行命名
        String fileName = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();

        //构建File实例
        File f = new File("D:\\nginx\\html\\img\\"+fileName);

        //如果需要把图片上传到nginx
        //a-nginx和当前项目在同一个计算机中 - file -> html的绝对路径
        //b-nginx如何和当前项目不再同一个计算机中 - commons-net

        //写入到磁盘中
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }

        req.getSession().setAttribute("picture",fileName);

        return new Result("200","文件上传成功!",fileName);
    }

    @PostMapping("/layui/upload/nginx2")
    public @ResponseBody Result uploads2(HttpServletRequest req,@RequestParam("file") MultipartFile file){
        //重新进行命名
        String fileName = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();

        //构建File实例
        File f = new File("D:\\nginx\\html\\img\\"+fileName);

        //如果需要把图片上传到nginx
        //a-nginx和当前项目在同一个计算机中 - file -> html的绝对路径
        //b-nginx如何和当前项目不再同一个计算机中 - commons-net

        //写入到磁盘中
        try {
            file.transferTo(f);
        } catch (IOException e) {
            e.printStackTrace();
        }

        req.getSession().setAttribute("imgUrl",fileName);

        return new Result("200","文件上传成功!",fileName);
    }

    @PostMapping("/layui/upload/nginx3")
    public @ResponseBody Result uploads3(HttpServletRequest req,@RequestParam("file") MultipartFile file){

        for(int i=1;i<8;i++){
           if( req.getSession().getAttribute("image"+i)==null){
               //重新进行命名
               String fileName = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();

               req.getSession().setAttribute("image"+i,fileName);
               System.out.println(req.getSession().getAttribute("image"+i));
               //构建File实例
               File f = new File("D:\\nginx\\html\\img\\"+fileName);

               //如果需要把图片上传到nginx
               //a-nginx和当前项目在同一个计算机中 - file -> html的绝对路径
               //b-nginx如何和当前项目不再同一个计算机中 - commons-net

               //写入到磁盘中
               try {
                   file.transferTo(f);
               } catch (IOException e) {
                   e.printStackTrace();
               }
               return new Result("200","文件上传成功!",fileName);
           }

        }
        return new Result("500","文件上传失败!");

    }

    //点击发布房源并且数据插入表中（整租）
    @RequestMapping("/addHouse")
    public String addHouse(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        //处理乱码
        response.setContentType("text/json;charset=utf-8");
        int count1 = 0;//学生
        int count2 = 0;//白领
        int count3 = 0;//家庭


        //周边环境设施表
        String fridge = request.getParameter("h1");
        String television = request.getParameter("h2");
        String airCondition = request.getParameter("h3");
        String geyser = request.getParameter("h4");
        String washingMachine = request.getParameter("h5");
        String broadband = request.getParameter("h6");
        String sofa = request.getParameter("h7");
        String balcony = request.getParameter("h8");
        String gasStove = request.getParameter("h9");
        String rangeHood = request.getParameter("h10");
        String wardrobe = request.getParameter("h11");
        String heat = request.getParameter("h12");
        String bed = request.getParameter("h13");
        String intelligentLock = request.getParameter("h14");
        String greenery = request.getParameter("h15");
        String schoolNearbyHouse = request.getParameter("h16");
        String cookingable = request.getParameter("h17");
        String bathroom = request.getParameter("h18");
        String trafficConvenient = request.getParameter("h19");
        String shoppingConvenient = request.getParameter("h20");

        //房源表
        String agentId = request.getParameter("agentId");
        String landlordId = request.getParameter("landlordId");
        String evaluate = request.getParameter("evaluate");
        String require = request.getParameter("require");
        String picture = (String) request.getSession().getAttribute("picture");
        //System.out.println(picture);
        String type = request.getParameter("type");
        String area = request.getParameter("area");
        String floor = request.getParameter("floor");
        String car = request.getParameter("car");
        String date = request.getParameter("date");
        String direction = request.getParameter("direction");
        String city = request.getParameter("city");
        String rent = request.getParameter("rent");
        String state = request.getParameter("state");
        String money = request.getParameter("money");
        String name = request.getParameter("name");
        String number = request.getParameter("number");
        String imgUrl = (String) request.getSession().getAttribute("imgUrl");


        //权重判别房源身份（学生，白领，房源）
        String house_identity = "其它";
        if (type == "小户型") {
            count1 += 1;
        } else if (type == "中户型") {
            count3 += 2;
        } else {
            count2 += 3;
        }
        if (area == "大于89平米") {
            count3 += 1;
        } else {
            count1 += 1;
            count2 += 1;
        }
        if (car == "true") {
            count2 += 1;
            count3 += 1;
        }
        if (fridge == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }
        if (television == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (broadband == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (balcony == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (gasStove == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }
        if (rangeHood == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (intelligentLock == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (greenery == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (schoolNearbyHouse == "true") {
            count1 += 1;
            count2 += 0;
            count3 += 0;
        }
        if (trafficConvenient == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }

        //权重判断
        if (count1 > count2 && count1 > count3) {
            house_identity = "学生";
        } else if (count2 > count3) {
            house_identity = "白领";
        }

        //房源表设置值
        House house = new House(Integer.valueOf(agentId),
                Integer.valueOf(landlordId),evaluate,require,
                picture,type,area,Integer.valueOf(floor),car,
                date,direction,city,rent,state,
                Double.valueOf(money),house_identity,number,name,imgUrl);

        //房源表插值
        //houseService.insertHouse(house);
        houseService.insertHouse2(house);

        //查询house_id
        Integer house_id = houseService.selectDoorPlate(number,name);

        //周边环境设施表设置值
        EnvironmentFaclity environmentFaclity = new EnvironmentFaclity(house_id, fridge,
                television, airCondition, geyser, washingMachine, broadband, sofa, balcony,
                gasStove, rangeHood, wardrobe, heat, bed, intelligentLock, greenery,
                schoolNearbyHouse, cookingable, bathroom, trafficConvenient, shoppingConvenient);

        //周边环境设施表插值
        environmentFacilityService.insert(environmentFaclity);

        List<String> images = new ArrayList<>();
        for(int i=1;i<8;i++) {
            if (request.getSession().getAttribute("image" + i) != null) {
                System.out.println((String) request.getSession().getAttribute("image" + i));
                images.add((String) request.getSession().getAttribute("image" + i));
                request.getSession().removeAttribute("image"+i);
            }
        }


        for (String image : images) {
            Image image1 = new Image(house_id,image);
            iImageService.insert(image1);
        }
        iCostService.insert(new Cost(house_id,Double.valueOf(money),Double.valueOf(money)/3,500.0));
        return "/home_page/home";
    }


    //点击发布房源并且数据插入表中（合租）
    @RequestMapping("/addHouse2")
    public String addHouse2(HttpServletRequest request, HttpServletResponse response) throws ParseException {
        response.setContentType("text/json;charset=utf-8");
        int count1 = 0;//学生
        int count2 = 0;//白领
        int count3 = 0;//家庭

        //房源表
        String agentId = request.getParameter("agentId");
        String landlordId = request.getParameter("landlordId");
        String evaluate = request.getParameter("evaluate");
        String require = request.getParameter("require");
        String picture = (String) request.getSession().getAttribute("picture");
        //String picture = request.getParameter("picture");
        String type = request.getParameter("type");
        String area = request.getParameter("area");
        String floor = request.getParameter("floor");
        String car = request.getParameter("car");
        String date = request.getParameter("date");
        String direction = request.getParameter("direction");
        String city = request.getParameter("city");
        String rent = request.getParameter("rent");
        String state = request.getParameter("state");
        String money = request.getParameter("money");
        String name = request.getParameter("name");
        String number = request.getParameter("number");
        String imgUrl = (String) request.getSession().getAttribute("imgUrl");

        //合租要求表


        String tenantStable = request.getParameter("box1");
        String family = request.getParameter("box2");
        String gender = request.getParameter("box3");
        String workRestNormal = request.getParameter("box4");
        String forbidSmoke = request.getParameter("box5");
        String forbidPet = request.getParameter("box6");


        //周边环境设施表
        //String house_id = request.getParameter("house_id");
        String fridge = request.getParameter("h1");
        String television = request.getParameter("h2");
        String airCondition = request.getParameter("h3");
        String geyser = request.getParameter("h4");
        String washingMachine = request.getParameter("h5");
        String broadband = request.getParameter("h6");
        String sofa = request.getParameter("h7");
        String balcony = request.getParameter("h8");
        String gasStove = request.getParameter("h9");
        String rangeHood = request.getParameter("h10");
        String wardrobe = request.getParameter("h11");
        String heat = request.getParameter("h12");
        String bed = request.getParameter("h13");
        String intelligentLock = request.getParameter("h14");
        String greenery = request.getParameter("h15");
        String schoolNearbyHouse = request.getParameter("h16");
        String cookingable = request.getParameter("h17");
        String bathroom = request.getParameter("h18");
        String trafficConvenient = request.getParameter("h19");
        String shoppingConvenient = request.getParameter("h20");

        //与整租相同，权重判别
        String house_identity = "其它";
        if (type == "小户型") {
            count1 += 1;
        } else if (type == "中户型") {
            count3 += 2;
        } else {
            count2 += 3;
        }
        if (area == "大于89平米") {
            count3 += 1;
        } else {
            count1 += 1;
            count2 += 1;
        }
        if (car == "true") {
            count2 += 1;
            count3 += 1;
        }
        if (fridge == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }
        if (television == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (broadband == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (balcony == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (gasStove == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }
        if (rangeHood == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (intelligentLock == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (greenery == "true") {
            count1 += 0;
            count2 += 0;
            count3 += 1;
        }
        if (schoolNearbyHouse == "true") {
            count1 += 10;
            count2 += 0;
            count3 += 0;
        }
        if (trafficConvenient == "true") {
            count1 += 0;
            count2 += 1;
            count3 += 1;
        }

        //权重判断
        if (count1 > count2 && count1 > count3) {
            house_identity = "学生";
        } else if (count2 > count3) {
            house_identity = "白领";
        }

        //房源表设置值
        House house = new House(Integer.valueOf(agentId),
                Integer.valueOf(landlordId),evaluate,require,
                picture,type,area,Integer.valueOf(floor),car,
                date,direction,city,rent,state,
                Double.valueOf(money),house_identity,number,name,imgUrl);

        //房源表插值
        houseService.insertHouse2(house);

        //查询house_id
        Integer house_id = houseService.selectDoorPlate(number,name);

        request.setAttribute("house_id", house_id);

        //合租要求设置值
        CotenancyRequire cotenancyRequire = new CotenancyRequire(Integer.valueOf(landlordId),
                family,gender,forbidPet, tenantStable, workRestNormal, forbidSmoke, house_id);

        //合租要求插值
        cotenancyRequireService.insert(cotenancyRequire);

        //周边环境设置值
        EnvironmentFaclity environmentFaclity = new EnvironmentFaclity(house_id, fridge,
                television, airCondition, geyser, washingMachine, broadband, sofa, balcony,
                gasStove, rangeHood, wardrobe, heat, bed, intelligentLock, greenery,
                schoolNearbyHouse, cookingable, bathroom, trafficConvenient, shoppingConvenient);

        //周边环境插值
        environmentFacilityService.insert(environmentFaclity);

        List<String> images = new ArrayList<>();
        for(int i=1;i<8;i++) {
            if (request.getSession().getAttribute("image" + i) != null) {
                System.out.println((String) request.getSession().getAttribute("image" + i));
                images.add((String) request.getSession().getAttribute("image" + i));
                request.getSession().removeAttribute("image"+i);
            }
        }


        for (String image : images) {
            Image image1 = new Image(house_id,image);
            iImageService.insert(image1);
        }
        iCostService.insert(new Cost(house_id,Double.valueOf(money),Double.valueOf(money)/3,500.0));
        return "/home_page/home";
    }

}